package main

import (
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

type School struct {
	gorm.Model
	Name         string
	HeadMasterID uint //名字必须 <对方实体的结构体名字+其主键名>
}
type HeadMaster struct {
	gorm.Model
	Name   string
	School School //必须使用命名方式，匿名方式就直接把School的字段合并到HeadMaster中了
}

func main() {
	dsn := "root:hedaodao@(127.0.0.1:3306)/gorm_class?charset=utf8mb4&parseTime=True&loc=Local"
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		SkipDefaultTransaction:                   false,
		DisableForeignKeyConstraintWhenMigrating: true,
	})
	if err != nil {
		panic(err)
	}

	//迁移时，必须指定School、HeadMaster两个表
	db.AutoMigrate(&School{}, &HeadMaster{})

	//创建实例的时候，不用手动处理校长表中学校外键，GORM会自动填写这个外键值
	school := School{
		Model: gorm.Model{
			ID: 2,
		},
		Name: "希望小学",
	}
	master := HeadMaster{
		Model: gorm.Model{
			ID: 1,
		},
		Name:   "校长一号",
		School: school,
	}
	//校长结构中是两个表的全量数据
	db.Create(&master)
}
